'''
selenium破解图鉴网站验证码
'''
from ttapi import base64_api
from selenium import webdriver
# 处理图片库
from PIL import Image
import time

class Ttspider:
    def __init__(self):
        self.driver = webdriver.Chrome()
        self.driver.get(url='http://www.ttshitu.com/login.html?spm=null')

    def get_verify_image(self):
        """获取验证码截图"""
        # 获取登录页截图
        self.driver.save_screenshot('index.png')
        # 获取验证码图片坐标(左上角xy 右下角xy)
        img_node = self.driver.find_element_by_id('captchaImg')
        # 左上角: location属性 {'x':ss, 'y':ss}
        locate_dict = img_node.location
        left_x = locate_dict['x']
        left_y = locate_dict['y']
        # 右下角:size属性{'height':x, 'width':x}
        size_dict = img_node.size
        right_x = left_x + size_dict['width']
        right_y = left_y + size_dict['height']
        # 截取图片
        img = Image.open('index.png').crop((left_x, left_y, right_x, right_y))
        img.save('verify.png')

    def login(self):
        """登录图鉴网站"""
        while True:
            try:
                # 获取验证码
                self.get_verify_image()
                # 在线识别
                result = base64_api('hacker001', 'zhanshen001', 'verify.png', 7)
                # 定位节点,开始登录
                # 用户名、密码、验证码
                self.driver.find_element_by_name('userName').send_keys('hacker001')
                self.driver.find_element_by_name('password').send_keys('zhanshen001')
                self.driver.find_element_by_name('captcha').send_keys(result)
                # 登录按钮
                self.driver.find_element_by_xpath('/html/body/div/div/div[2]/form/button').click()
                # 休眠
                time.sleep(1)
                self.driver.find_element_by_xpath('//*[@id="userBalance"]')
                # 正常数据代码
                break
            except Exception as e:
                pass

if __name__ == '__main__':
    spider = Ttspider()
    spider.login()





















